package logic

import (
	"context"
	"doctor-medicine-system/pkg"
	"net/http"
	"path/filepath"

	"doctor-medicine-system/api/internal/svc"
	"doctor-medicine-system/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadApiLogic {
	return &UploadApiLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadApiLogic) UploadApi(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("file")
	if err != nil {
		return &types.Response{
			Message: "文件未上传",
			Data:    nil,
			Code:    500,
		}, nil
	}
	ext := filepath.Ext(m.Filename)
	if ext != ".jpg" && ext != ".webp" && ext != ".svg" {
		return &types.Response{
			Message: "格式错误",
			Data:    nil,
			Code:    500,
		}, nil
	}
	if m.Size >= 5*1024*1024 {
		return &types.Response{
			Message: "图片上传最大限制为5MB",
			Data:    nil,
			Code:    500,
		}, nil
	}
	upload, err := pkg.Upload(file, m)
	if err != nil {
		return &types.Response{
			Message: "上传失败",
			Data:    nil,
			Code:    500,
		}, nil
	}
	return &types.Response{
		Message: "上传成功",
		Data:    upload,
		Code:    200,
	}, nil
}
